$(document).ready(function(){
  var iosocket = io.connect();
  var username = sessionStorage.username;
  iosocket.emit('loginIn',username);
  $(".username").text(sessionStorage.username);
  if(sessionStorage.username==undefined){
    location.href = "/login";
  }
  $(".loginOut").click(function(){
    iosocket.emit('loginOut',username);
    location.href = "/login";
  });
  $(".btn-blue").click(function(){
    var text = $(".mesbox").val();
    if (text!="") {
      var data = {
        name:sessionStorage.username,
        content:text
      }
      iosocket.emit('messageClient',data);
      $('.mesbox').val('');
      sendHtml(username,text);
    }
  });
  iosocket.on('connect', function () {
    //加入聊天室
      iosocket.on('loginInServer', function(msg) {
          loginInHtml(msg);
      });
    //离开聊天室
      iosocket.on('loginOutServer', function(msg) {
        loginOutHtml(msg);
      });
    //获取消息
      iosocket.on('messageServer', function(msg) {
          reciveHtml(msg.name,msg.content);
      });
  });
});
function sendHtml(name,content){
  var html = "";
  html += '<div class="send">'+
            '<div class="sendname">'+name+'</div>'+
            '<div class="sendBox">'+
              '<div class="arrow"></div>'+
              content+
            '</div>'+
            '<div class="clear"></div>'+
          '</div>';
  $(".room").append(html);
  $('.room').scrollTop( $('.room')[0].scrollHeight );
}
function reciveHtml(name,content){
  var html = "";
  html += '<div class="recive">'+
            '<div class="recivename">'+name+'</div>'+
            '<div class="reciveBox">'+
              '<div class="arrow"></div>'+
              content+
            '</div>'+
            '<div class="clear"></div>'+
          '</div>';
  $(".room").append(html);
  $('.room').scrollTop( $('.room')[0].scrollHeight );
}
function loginInHtml(name){
  var html = "";
  html = '<div class="brocast">'+name+'加入聊天室</div>';
  $(".room").append(html);
  $('.room').scrollTop( $('.room')[0].scrollHeight );
}
function loginOutHtml(name){
  var html = "";
  html = '<div class="brocast">'+name+'离开聊天室</div>';
  $(".room").append(html);
  $('.room').scrollTop( $('.room')[0].scrollHeight );
}
document.onkeydown = function(e){
  var ev = document.all ? window.event : e;
  if(ev.keyCode==13) {
    $(".btn-blue").click();
   }
}
